package middleware

import (
	"errors"
	"fmt"
	"gintify/core"
	"gintify/model"
	"gintify/response"
	"github.com/gin-gonic/gin"
)

//拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, _ := c.Get("user")
		user := claims.(model.SysUser)

		//获取请求的URI
		obj := c.Request.URL.RequestURI()
		//获取请求方法
		act := c.Request.Method

		//获取用户的角色Name
		sub := user.Role.Name

		fmt.Printf("sub: %s obj: %s act: %s\n", sub, obj, act)


		//判断策略中是否存在
		ok, err := core.CE.Enforce(sub, obj, act)
		if err != nil {
			response.Fail(c, "Casbin服务出错", err)
			c.Abort()
		}
		if user.RoleID == 1 || ok{ // Administrator 直接验证通过
		//if ok{
			c.Next()
		} else {
			response.Fail(c, "权限不足", errors.New("Casbin验证未通过"))
			c.Abort()
			return
		}
	}
}
